<template>
  <div ref="uploadImgBox" @paste="handlePaste"
    @mousemove="handleMouseMove"
    @mouseenter="mouseenter"
    @mouseleave="mouseleave"
    tabindex="0"
    @focus="handleFocus"
    @blur="handleBlur"
    class="upload-box" :class="{ 'hiddenupload': imgShowList.length>=1||uploading}">
    <!-- 只上传一张图片的处理 -->
    <el-upload :drag="drag" :action="uploadImgUrl" accept="image/*" :file-list="imgShowList" :show-file-list="true" list-type="picture-card" :limit="1" :on-success="success" :disabled="disabled" :http-request="uploadImgs" :before-upload="beforeUpload" :on-remove="handleRemove" :on-preview="handlePictureCardPreview">
      <div class="uploadbg">
        <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
        <br />
        <span>上传图片</span>
      </div>
    </el-upload>
    <div v-if="showSaoma" class="btn">
      <saomaUpload @success="uploadSuccess">
        <el-button type="primary" plain>扫码上传</el-button>
      </saomaUpload>
    </div>

  </div>
</template>

<script>
import saomaUpload from "./saomaUpload.vue";
import { uploadFileFn } from "../../api/upload"; 
export default {
  props: {
    headers: {
      default: null,
    },
    multiple: {
      default: true,
    },
    data: {
      default: null,
    },
    name: {
      default: "file",
    },
    drag: {
      default: true,
    },
    accept: {
      default: null,
    },
    limit: {
      default: 10,
    },
    // oldList: {
    //   default: [],
    // },
    disabled: {
      default: false,
    },
    value: {
      default: "",
    },
    showSaoma:{
      default: true,
    },
  },
  name: "uploadImageOne",
  components: { saomaUpload },
  data() {
    return {
      uploadImgUrl: "",
      imgShowList: [],
      imgUrl: "",
      uploading:false,
      isMouseInside:false,
      imageBlob:null,
      mousePosition:{
        x:0,
        y:0
      },
      hasFocus:false


    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo;
    }
  },
  watch: {
    value: {
      handler(val) {
        this.imgUrl = val;
        if (this.imgUrl) {
          this.imgShowList = [
            {
              name: "",
              url: this.imgUrl,
            },
          ];
        } else {
          this.imgShowList = [];
        }
      },
      immediate: true,
      // deep: true,
    },
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    emitUrl(){
      this.$emit("change", this.imgUrl);
      this.$emit("input", this.imgUrl);
    },
    beforeUpload(file){
      this.uploading = true
      return true
    },
    uploadSuccess(e) {
      if (e && e.length) {
        // 取得新上传的文件
        this.imgUrl = e[0].url;

        this.emitUrl()
        // this.imgShowList = [
        //   {
        //     name: "",
        //     url: this.imgUrl,
        //   },
        // ];
      }
    },
    // 图片删除
    handleRemove(response, fileList, file) {
      this.imgShowList = [];
      this.imgUrl = "";
      this.emitUrl();
    },
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    exceed() {
      this.$alert(`最多上传1张图片！`);
    },
    // 图片上传成功
    success(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.uploading = false
        this.imgUrl = res.data.filePath;
        this.emitUrl();
      }
    },

    // 上传图片
    async uploadImgs(file) {
      // console.log("%c Line:466 🍆 压缩前file", "color:#2eafb0", file);
      // 获取压缩后的文件流
      let compreeBolb = await this.compressImage(file);
      // console.log(
      //   "%c Line:468 🎂 压缩后compreeBolb",
      //   "color:#33a5ff",
      //   compreeBolb
      // );
      // const formData = new FormData();
      // formData.append("file", compreeBolb); //压缩后的文件会自动转换成二进制文件流类型
      //上传图片到后台
      try {
        // let uploadImg = await postUpload(formData);
        const resFile = await uploadFileFn(compreeBolb, this.userInfo.tenantId);
        const imgUrl = qiniu.imageMogr2(
          {
            strip: true, // 布尔值，是否去除图片中的元信息
            quality: 90, // 图片质量，取值范围1-100
            format: "jpg", // 新图的输出格式，取值范围：jpg，gif，png，webp等
          },
          resFile.key,
          resFile.domain
        );
        file.data = {
          filePath: decodeURIComponent(imgUrl),
        };
        file.code = 200;
        return file;
      } catch {
        file.code = 500;
        return file;
      }
    },

    
    handleMouseMove(event) {
      if(this.$refs.uploadImgBox){
        const rect = this.$refs.uploadImgBox.getBoundingClientRect()
        this.mousePosition = {
          x: event.clientX - rect.left,
          y: event.clientY - rect.top
        }
      }
      
    },

    handleFocus() {
      this.hasFocus = true
    },
    handleBlur() {
      this.hasFocus = false
    },
    mouseenter(){
      this.isMouseInside = true
      console.log("%c Line:212 🍋 this.isMouseInside", "color:#465975", this.isMouseInside);
      this.$refs.uploadImgBox.focus() // 鼠标进入时自动聚焦
    },
    mouseleave(){
      this.isMouseInside = false
    },
    // 处理粘贴图片的逻辑
    // 粘贴监听
    async handlePaste(event) {
      // 如果鼠标不在区域内，不处理
      if (!this.isMouseInside||!this.hasFocus) {
        console.log('忽略粘贴：鼠标不在区域内')
        return
      }
      
      event.preventDefault()
      const clipboardData = event.clipboardData || window.clipboardData
      console.log("%c Line:228 🥝 clipboardData", "color:#b03734", clipboardData);
      
      if (!clipboardData) {
        console.warn('无法访问剪切板数据')
        return
      }
      
      // 检查是否有文件（图片文件）
      if (clipboardData.files && clipboardData.files.length > 0) {
        const file = clipboardData.files[0]
        console.log("%c Line:242 🎂图片文件 file", "color:#3f7cff", file);
        if (file.type.startsWith('image/')) {
          await this.processImageBlob(file, 'file')
          return
        }
      }
      // 检查items中的图片数据
      if (clipboardData.items) {
        const item = clipboardData.items[0]
          if (item.type.indexOf('image') !== -1) {
            const blob = item.getAsFile()
            if (blob) {
              await this.processImageBlob(blob, 'clipboard-data')
              return
            }
          }
        // for (let i = 0; i < clipboardData.items.length; i++) {
          
        // }
      }
      this.$message.error('剪切板中没有找到图片数据')
    },
    // 处理粘贴的图片
    async processImageBlob(blob, source) {
      // 上传图片
      const onlineUrl = await this.uploadImgs({
        file:blob
      })
      this.success(onlineUrl)
      if(onlineUrl.code==200){
         // 回显
        this.imgShowList = [{
          url:onlineUrl.data.filePath,
          name:''
        }]
      }
     
    }


  },
};
</script>
<style scoped lang="scss">
.upload-box{
  position: relative;
  .btn{
    width: 90px;
    // position: absolute;
    // left: 110px;
    // top: 0;
  }
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}
::v-deep .el-upload--picture-card {
  border: none;
  background-color: #f0f4ff;
  width: 100px;
  height: 100px;
  margin-bottom: 10px;
  .el-upload-dragger {
    border: none;
    width: 100%;
    height: 100%;
    background-color: transparent;
  }
  .uploadbg {
    line-height: 26px;
    padding-top: 10px;
    img {
      width: 54px;
      // height: 48px;
    }
    span {
      color: #808191;
    }
  }
}
</style>
